package com.ran.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ran.common.vo.JwtHelper;
import com.ran.common.vo.MD5;
import com.ran.sys.entity.User;
import com.ran.sys.mapper.UserMapper;
import com.ran.sys.service.IUserService;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;


@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {


    @Override
    public User getUserInfoByUserName(String username) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username",username);
        User user = baseMapper.selectOne(wrapper);
        if (user.getId() == null){
            return null;
        }
        return user;
    }

    @Override
    public User getUserInfoByUserId(String userid) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("id",userid);
        return baseMapper.selectOne(wrapper);

    }

    @Override
    public Map<String, Object> userlogin(User user1, User user2) {

        //判断密码是否一致
        String md5Password = MD5.encrypt(user2.getPassword());
        if (!user1.getPassword().equals(md5Password)) {
            return null;
        }

        //根据userid和username生成token字符串，通过map返回
        String token = JwtHelper.createToken( user1.getId().toString(), user2.getUsername());

        Map<String, Object> data = new HashMap<>();
        data.put("token", token);
        return data;
    }


    @Override
    public User userregister(User user) {
        //把输入密码进行加密 MD5
        String encrypt = MD5.encrypt(user.getPassword());
        user.setPassword(encrypt);
        return user;
    }

    @Override
    public User userUpdate(HttpServletRequest request,User user) {
        String token = request.getHeader("token");
        if (token == null) {
            return null;
        }
        String userId = JwtHelper.getUserId(token);
        if (userId == null) {
           return null;
        }
        User User = getUserInfoByUserId(userId);
        if (!User.getUsername().equals(user.getUsername())) {
           return null;
        }
        user.setId(Integer.parseInt(userId));
        String encrypt = MD5.encrypt(user.getPassword());
        user.setPassword(encrypt);
        return user;
    }



}
